import axios, { AxiosRequestConfig, ResponseType, AxiosInstance } from 'axios'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import md5 from 'js-md5'
const TIMEOUT = 40000
const MIME_TYPE: IDictionary<ResponseType> = {
  JSON: 'json',
}

const createInstance = () => {
  const instance = axios.create({
    baseURL: `${import.meta.env.VITE_APP_WEB_URL}`,
    // baseURL: 'http://192.168.0.125:8904',
    withCredentials: true,
    timeout: TIMEOUT,
    responseType: MIME_TYPE.JSON,
  })

  instance.interceptors.request.use(handleConfig)

  instance.interceptors.response.use(handleResponse, handleError)

  return instance
}

const handleConfig = (config: any) => {
  // 授权参数
  const apiKey = 'kuke.com'
  const apiSecret = 'ce873749-de33-486b-8304-bccc31e6e31d'
  const time = new Date().getTime()
  const authCode = {
    apiKey: 'kuke.com',
    sign: md5(apiKey + apiSecret + time) + time,
    userId: '1845392568',
    snid: '192.168.1.12',
  }
  config.data = Object.assign(config.data, authCode)
  config.headers['Content-Type'] =
    'application/x-www-form-urlencoded;charset=UTF-8'
  if (
    config.data &&
    config.headers['Content-Type'] ===
      'application/x-www-form-urlencoded;charset=UTF-8'
  ) {
    config.data = qs.stringify(config.data)
  }
  return config
}

const handleResponse = (response: any) => {
  return response.data
}

const handleError = (error: any) => {
  const { response, message } = error
  return Promise.reject(
    response ? new Error(response.data.message || message) : error,
  )
}

const toastError = (error: any) => {
  const { response, message } = error

  ElMessage({
    message: response?.data?.message || message,
    type: 'success',
  })

  return Promise.reject(error)
}

interface Instance extends AxiosInstance {
  (config: AxiosRequestConfig): Promise<any>
}
export const requestWithoutErrorToast: Instance = createInstance()

const request: Instance = createInstance()
request.interceptors.response.use(undefined, toastError)

export default request
